<!-- 继承页面模板 -->
{% extends 'layout/layui_base_page.html' %}

<!-- 加载静态文件 -->
{% load static %}

<!-- Title -->
{% block title %}
    员工信息
{% endblock %}

<!-- CSS --->
{% block css %}
    <style>
        #assignTrainArea .layui-inline {
            width: 250px;
        }
    </style>
{% endblock %}

<!-- Content -->
{% block content %}
    <!-- 01: 面包屑导航 -->
    <span class="layui-breadcrumb">
      <a href="javascript:;">首页</a>
      <a href="javascript:;">基础数据</a>
      <a><b>员工信息</b></a>
    </span>

    <!-- 02: 查询区域 --->
    <div id="queryArea" style="margin-top: 20px;">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="q_str"><b>查询条件：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="q_str" id="q_str" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" style="width: 100px"><i class="fa fa-search"></i>&nbsp;&nbsp;查询
                    </button>
                    <button type="button" class="layui-btn" style="width: 100px"><i class="fa fa-list"></i>&nbsp;&nbsp;全部
                    </button>
                </div>
            </div>
        </form>

    </div>

    <!-- 03：表格区域 -->
    <table class="layui-hide" id="employeeTable" lay-filter="employeeTable"></table>

    <!-- 04: 表格中的按钮 -->
    <script type="text/html" id="tableButton">
        <a class="layui-btn layui-btn-xs" lay-event="assign">
            <i class="fa fa-edit" aria-label="true"></i>&nbsp;安排培训
        </a>
    </script>

    <!-- 05: 分配职位培训表格中的按钮 -->
    <script type="text/html" id="assignTableButton">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del_position">
            <i class="fa fa-trash" aria-label="true"></i>&nbsp; 删除
        </a>
    </script>

    <!-- 06: 安排培训的弹出层 -->
    <div id="assignTrainArea" style="display: none;padding: 30px 20px">
        <form class="layui-form">
            {% csrf_token %}
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="eid"><b>员工编号：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="eid" id="eid" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="name"><b>员工姓名：</b></label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" class="layui-input" readonly
                               style="background-color: #eaeaea">
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="line"><b>产线：</b></label>
                    <div class="layui-input-block">
                        <div id="line" class="xm-select-demo"></div>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="department"><b>部门：</b></label>
                    <div class="layui-input-block">
                        <div id="department" class="xm-select-demo"></div>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="position"><b>职位：</b></label>
                    <div class="layui-input-block">
                        <div id="position" class="xm-select-demo"></div>
                    </div>
                </div>
                <div class="layui-inline" style="width:150px;">
                    <button type="button" id="btnAssign" class="layui-btn layui-btn-normal">
                        <i class="fa fa-hand-o-right" aria-hidden="true"></i> &nbsp; 确认安排
                    </button>
                </div>
            </div>
        </form>

        <table class="layui-hide" id="assignedTrainTable" lay-filter="assignedTrainTable"></table>

    </div>
{% endblock %}

<!-- JS -->
{% block js %}
    <script src="{% static 'js/xm-select.js' %}"></script>
    <script>
        // 入口函数
        $(function () {
            // === 页面初始化 ===
            initPage();
            // === 响应按钮的点击事件===
            buttonClick();
            // === 表格的初始化 ===
            initTable();
            // ==== 初始化选择培训的联级下拉框
            initXMSelect();
        });

        // ================ 页面初始化的实现 ==================
        function initPage() {
            layui.use(['element'], function () {
                let element = layui.element;
            })
        }

        // =============== 按钮点击的功能实现 =================
        function buttonClick() {
            // === 安排培训 ===
            $('#btnAssign').on('click', function () {
                // 获取选中的职位
                let selectValue = xmSelect.get('#position', true).getValue('valueStr');


                // ====== 使用Ajax 提交  ====
                $.ajax({
                    url: "{% url 'add_trainee' %}"
                    , method: 'post'
                    , data: {
                        position: selectValue,
                        eid: $('#eid').val(),
                        name: $('#name').val(),
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    }
                    , success: function (res) {
                        if (res.status) {
                            layui.layer.msg("添加成功！");
                            // 刷新表格
                            initAssignedTable($('#eid').val());
                        } else {
                            layui.layer.msg(res.error, {
                                icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭'],
                            });
                        }
                    }
                })

            });
        }

        // ================ 表格初始化的实现 ==================
        function initTable() {
            layui.use(['table', 'form'], function () {
                var table = layui.table;
                let form = layui.form;
                // ==== 渲染表格 =====
                table.render({
                    elem: $('#employeeTable')
                    , url: "{% url 'list_employee' %}"
                    , method: "post"
                    , where: {
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 60, title: '序号', align: 'center', sort: true}
                        , {field: 'eid', width: 150, title: '工号', align: 'center'}
                        , {field: 'name', title: '姓名', align: 'center', sort: true}
                        , {
                            field: 'status', title: '状态', align: 'center', sort: true,
                            templet: function (res) {
                                // res-- 渲染的一行数据   res.status --- 这一行的状态值
                                if (res.status) {
                                    return "<input type='checkbox' value='" + res.eid + "' lay-filter='changeEmpStatus' lay-skin='switch' lay-text='在职|离职' checked >"
                                } else {
                                    return "<input type='checkbox' value='" + res.eid + "' lay-filter='changeEmpStatus' lay-skin='switch' lay-text='在职|离职' >"
                                }
                            }
                        }
                        , {field: 'birthday', title: '出生日期', align: 'center', sort: true}
                        , {field: 'mobile', title: '电话', align: 'center', sort: true}
                        , {field: 'email', title: '邮箱', align: 'center', sort: true}
                        , {field: 'employment_time', title: '入职时间', align: 'center', sort: true}
                        , {fixed: 'right', title: "操作", width: 120, align: 'center', toolbar: '#tableButton'}
                    ]]
                    , page: true
                    , limit: 15
                    , limits: [15, 20, 25, 30, 50, 100]
                    , done: function (res, curr, count) {
                        // 设置表头的样式
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }
                });

                // ==== 响应表格中按钮的点击事件====
                table.on('tool(employeeTable)', function (obj) {
                    // 获取点击行的数据
                    let oneLineData = obj.data;
                    // 判断点击的按钮
                    if (obj.event === 'assign') {
                        assignTrainLayer(oneLineData);
                    }

                });

                // ===== 表格中表单元素的事件响应 ============
                form.on('switch(changeEmpStatus)', function (obj) {
                    // Ajax请求
                    $.ajax({
                        url: "{% url 'ch_employee_status' %}"
                        , method: 'post'
                        , data: {
                            eid: obj.value,
                            status:  obj.elem.checked ? 1 : 0,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , success: function (res) {
                            if (res.status){
                                location.reload();
                            } else {
                                layui.layer.msg(res.error, {
                                   icon:2,  area: ['400px','200px'], time:-1, btn:['关闭']
                                })
                            }
                        }
                    })

                })
            })
        }

        // ================ 已经安排培训职位的表格 =============
        function initAssignedTable(eid) {
            layui.use(['table'], function () {
                let table = layui.table;

                // === 渲染表格 ====
                table.render({
                    elem: '#assignedTrainTable'
                    , url: "{% url 'list_trainee_by_employee' %}"
                    , method: "post"
                    , where: {
                        eid: eid,
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 80, title: '序号', align: 'center'}
                        , {field: 'eid', width: 150, title: '工号', align: 'center'}
                        , {field: 'position__department__line__name', width: 100, title: '产线', align: 'center'}
                        , {field: 'position__department__name', width: 120, title: '部门', align: 'center'}
                        , {field: 'position__name', title: '职位', width: 150, align: 'center'}
                        , {field: 'create_time', title: '分配时间', align: 'center'}
                        , {fixed: 'right', title: "操作", width: 120, align: 'center', toolbar: '#assignTableButton'}
                    ]]
                    , page: true
                    , limit: 6
                    , limits: [6, 8, 10, 15, 20, 25, 30, 50, 100]
                    , done: function (res, curr, count) {
                        // 设置表头的样式
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }
                });

                // === 响应表格的事件 ===
                table.on('tool(assignedTrainTable)', function (obj) {
                    // 获取当前行的数据
                    let oneLineData = obj.data;
                    // 判断是否点击了删除按钮
                    if (obj.event === 'del_position') {
                        // 文字确认
                        let confirmStr = "是否确定删除【" + oneLineData.position__department__line__name +
                            "--" + oneLineData.position__department__name + "--" + oneLineData.position__name + "】信息?";
                        // 确认窗体
                        layui.layer.confirm(confirmStr, {
                            icon: 3, area: ['400px', '200px'], btn: ['确认', '取消'],
                        }, function (value, index, elem) {
                            // Ajax请求
                            $.ajax({
                                url: "{% url 'del_trainee' %}"
                                , method: 'post'
                                , data: {
                                    eid: oneLineData.eid,
                                    position_id: oneLineData.position_id,
                                    csrfmiddlewaretoken: "{{ csrf_token }}"
                                }
                                , success: function (res) {
                                    if (res.status) {
                                        layui.layer.msg("删除成功！");
                                        // 刷新表格
                                        initAssignedTable(oneLineData.eid);
                                    } else {
                                        layui.layer.msg(res.error, {
                                            icon: 2, area: ['400px', '200px'], time: -1, btn: ['关闭'],
                                        });
                                    }
                                }
                            })
                        })
                    }
                })
            })
        }

        // ================ 安排培训任务的弹出层 ===============
        function assignTrainLayer(value) {
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1
                    , title: "<b style='color:navy'>【安排培训】</b>"
                    , area: ['1000px', '600px']
                    , btn: ['关闭']
                    , content: $('#assignTrainArea')

                    // ========= 回调函数 ======
                    , success: function (index, layero) {
                        // 1.===== 在弹出层初始化工号和姓名 ====
                        $('#eid').val(value.eid);
                        $('#name').val(value.name);

                        // 2.==== 展示表格 ==================
                        initAssignedTable(value.eid);
                    }

                    , end: function (index, layero) {
                        // 重新初始化下拉库
                        initXMSelect();
                    }
                })
            });
        }

        // ================= 初始化联级下拉框 ==================
        function initXMSelect() {
            // === 初始化职位===
            let position_select = xmSelect.render({
                el: '#position'
                , name: 'position'
                , tips: "请选择职位"
                , filterable: true
                , height: '200px'
                , data: []
            });
            // === 初始化部门 ===
            let department_select = xmSelect.render({
                el: '#department'
                , name: 'department'
                , radio: true
                , clickClose: true
                , tips: "请选择部门"
                , filterable: true
                , height: '200px'
                , data: []
                , on: function (value) {
                    // Ajax请求
                    $.ajax({
                        'url': "{% url 'get_position_select' %}"
                        , method: 'post'
                        , data: {
                            department_id: value.arr[0].value,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , success: function (res) {
                            console.log(res);
                            position_select.update({data: res.data});
                        }
                    })
                }
            });
            // === 初始化产线 ===
            let line_select = xmSelect.render({
                el: '#line'
                , name: 'line'
                , radio: true
                , clickClose: true
                , tips: "请选择产线"
                , filterable: true
                , height: '200px'
                , data: []
                , on: function (value) {
                    // 当选中某一个产线的值的时候，执行的方法
                    // Ajax请求
                    $.ajax({
                        'url': "{% url 'get_department_select' %}"
                        , method: 'post'
                        , data: {
                            line_id: value.arr[0].value,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        }
                        , success: function (res) {
                            department_select.update({data: res.data});
                        }
                    })
                }
            });
            // === 请求line数据填充下拉框
            $.ajax({
                url: "{% url 'get_line_select' %}"
                , method: 'get'
                , success: function (res) {
                    // 把获取的值赋给xmselect
                    line_select.update({data: res.data});
                }
            });


        }
    </script>

{% endblock %}